package com.canal.admin.config;

import com.canal.admin.filter.TokenAuthenticationFilter;
import com.canal.admin.handler.TokenFailureHandler;
import com.canal.admin.handler.TokenRefreshSuccessHandler;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.authentication.logout.LogoutFilter;

/**
 * @author Administrator
 * @description
 * @date 2019年03月17 15:24
 */
public class TokenBasedConfigurer<T extends TokenBasedConfigurer<T,B>,B extends HttpSecurityBuilder<B>> extends AbstractHttpConfigurer<T,B> {

    private TokenAuthenticationFilter tokenAuthenticationFilter;

    public TokenBasedConfigurer() {
        this.tokenAuthenticationFilter = new TokenAuthenticationFilter();
    }

    @Override
    public void configure(B builder) throws Exception {
        //设置Filter使用的AuthenticationManager,这里取公共的即可
        tokenAuthenticationFilter.setAuthenticationManager(builder.getSharedObject(AuthenticationManager.class));
        //设置失败的Handler
        tokenAuthenticationFilter.setAuthenticationFailureHandler(new TokenFailureHandler());
        TokenAuthenticationFilter filter = postProcess(tokenAuthenticationFilter);
        builder.addFilterBefore(filter, LogoutFilter.class);
    }

    /**
     * 设置正确认证处理器
     * @param tokenRefreshSuccessHandler
     * @return
     */
    public TokenBasedConfigurer<T,B> tokenBasedSuccessHandler(TokenRefreshSuccessHandler tokenRefreshSuccessHandler) {
        tokenAuthenticationFilter.setAuthenticationSuccessHandler(tokenRefreshSuccessHandler);
        return this;
    }

    /**
     * 设置允许通过的请求
     * @param urls
     * @return
     */
    public TokenBasedConfigurer<T, B> permissiveRequestUrls(String... urls){
        tokenAuthenticationFilter.setPermissiveUrl(urls);
        return this;
    }
}
